package files

import (
	"dog-blog/base/logger"
	"io/ioutil"
	"net/http"
	"path"

	"gopkg.in/yaml.v2"
)

// LoadYaml 加载yml文件
func LoadYaml(filename string, out interface{}) error {
	bytes, err := ioutil.ReadFile(filename)
	if err != nil {
		logger.GetLogger().E(err.Error())
		return err
	}

	err = yaml.Unmarshal(bytes, out)
	if err != nil {
		logger.GetLogger().E(err.Error())
		return err
	}

	return nil
}

// LoadMdDir 加载本本地md文章
func LoadMdDir(dirname string) ([][]byte, error) {
	var byteList [][]byte

	filelist, err := ioutil.ReadDir(dirname)
	if err != nil {
		return byteList, err
	}

	for _, fileinfo := range filelist {
		if fileinfo.Mode().IsRegular() && path.Ext(fileinfo.Name()) == ".md" {
			bytes, err := ioutil.ReadFile(path.Join(dirname, fileinfo.Name()))
			if err != nil {
				logger.GetLogger().E(err.Error())
				continue
			}
			byteList = append(byteList, bytes)
		}
	}
	return byteList, err
}

// ReadRemoteMd 加载远程md文章
func ReadRemoteMd(urlPath string) ([][]byte, error) {
	var byteList [][]byte
	res, err := http.Get(urlPath)
	if err != nil {
		return byteList, err
	}
	defer res.Body.Close()

	bytes, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return byteList, err
	}
	// fmt.Printf("%s", bytes)
	byteList = append(byteList, bytes)
	return byteList, err
}
